package com.kotiln.lgc.aivoiceapp.service

import android.app.Service
import android.content.Intent
import android.os.Handler
import android.os.IBinder
import android.text.TextUtils
import android.view.View
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.airbnb.lottie.LottieAnimationView
import com.imooc.lib_voice.words.WordsTools
import com.kotiln.lgc.aivoiceapp.R
import com.kotiln.lgc.aivoiceapp.adapter.ChatListViewAdapter
import com.kotiln.lgc.aivoiceapp.data.ChatListData
import com.kotiln.lgc.aivoiceapp.entity.AppConstants
import com.kotiln.lgc.lib_base.helper.NotificationHelper
import com.kotiln.lgc.lib_base.helper.SoundPoolHelper
import com.kotiln.lgc.lib_base.helper.WindowHelper
import com.kotiln.lgc.lib_base.helper.`fun`.AppHelper
import com.kotiln.lgc.lib_base.util.LogUtil
import com.kotiln.lgc.lib_voice.engine.VoiceEngineAnalyze
import com.kotiln.lgc.lib_voice.impl.OnAsrResultListener
import com.kotiln.lgc.lib_voice.impl.OnNluResultListener
import com.kotiln.lgc.lib_voice.manager.VoiceManager
import com.kotiln.lgc.lib_voice.tts.VoiceTTS
import org.json.JSONObject

/**
 *@fileName VoiceService
 *@date2021/1/19  10:00
 *@author VoiceService$
 *@describe TODO
 *@desc 语音服务
 */
class VoiceService : Service(), OnNluResultListener {

    private val handler = Handler()

    private lateinit var mFullWindowView: View
    private lateinit var mChatListView: RecyclerView
    private lateinit var mLottieView: LottieAnimationView
    private lateinit var tvVoiceTips: TextView
    private val mList: MutableList<ChatListData> = mutableListOf<ChatListData>()
    private lateinit var mChatAdapter: ChatListViewAdapter

    override fun onBind(intent: Intent?): IBinder? {
        return null
    }

    override fun onCreate() {
        super.onCreate()
        LogUtil.i("语音服务启动")

        initCoreVoiceService()

    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        bindNotification()
        return START_STICKY_COMPATIBILITY
    }

    //绑定通知栏
    private fun bindNotification() {
        startForeground(1000, NotificationHelper.bindVoiceService("正在运行"))
    }

    //初始化语音服务
    private fun initCoreVoiceService() {

        WindowHelper.initHelper(this)
        mFullWindowView = WindowHelper.getView(R.layout.layout_window_item)
        mChatListView = mFullWindowView.findViewById<RecyclerView>(R.id.mChatListView)
        mLottieView=mFullWindowView.findViewById<LottieAnimationView>(R.id.mLottieView)
        tvVoiceTips=mFullWindowView.findViewById<TextView>(R.id.tvVoiceTips)
        mChatListView.layoutManager = LinearLayoutManager(this)
        mChatAdapter = ChatListViewAdapter(mList)
        mChatListView.adapter = mChatAdapter


        VoiceManager.initManager(this, object : OnAsrResultListener {
            override fun wakeUpReady() {
//                addAiText("唤醒引擎准备就绪")
                VoiceManager.ttsStart("唤醒引擎准备就绪")
            }

            override fun asrStartSpeak() {
                LogUtil.i("开始说话")
            }

            override fun asrStopSpeak() {
                LogUtil.i("结束说话")
//                hideWindow()
            }

            override fun wakeUpSuccess(result: JSONObject) {
                LogUtil.i("唤醒成功:$result")
                //当唤醒词是 东桑东桑 的时候,才开始识别
                val errorCode: Int = result.optInt("errorCode")
                //唤醒成功
                if (errorCode == 0) {
                    //唤醒词
                    val word: String = result.optString("word")
                    if (word == "东桑东桑") {
                        wakeUpFix()

                    }
                }
            }

            override fun updateUserText(text: String) {
                updateTips(text)
            }

            override fun asrResult(result: JSONObject) {
                LogUtil.i("=================result===================")
                LogUtil.i("result:$result")

            }

            override fun nluResult(nlu: JSONObject) {
                LogUtil.i("=================NLU===================")
                LogUtil.i("nlu:$nlu")
                VoiceEngineAnalyze.analyzeNlu(nlu, this@VoiceService)
//                hideWindow()
                addMineText(nlu.optString("raw_text"))
                addAiText(nlu.toString())
            }

            override fun voiceError(text: String) {
                LogUtil.e("发生错误:$text")
//                hideWindow()
            }

        })
    }

    /**
     * 唤醒成功后的操作
     */
    private fun wakeUpFix() {
        showWindow()
        updateTips("正在聆听...")
        SoundPoolHelper.play(R.raw.record_start)
        //应答
        val wakeUpText: String = WordsTools.wakeupWords()
        addAiText(wakeUpText, object : VoiceTTS.OnTTSResultListener {
            override fun ttsEnd() {
                //启动识别
                VoiceManager.startAsr()
            }

        })
    }


    //显示窗口
    private fun showWindow() {
        LogUtil.i("=======显示窗口========")
        mLottieView.playAnimation()
        WindowHelper.show(mFullWindowView)
    }

    //隐藏窗口
    private fun hideWindow() {
        LogUtil.i("=======隐藏窗口========")
        handler.postDelayed({
            WindowHelper.hide(mFullWindowView)
            mLottieView.pauseAnimation()
        }, 2000)
    }

    //打开App
    override fun openApp(appName: String) {
        if(!TextUtils.isEmpty(appName)){
            LogUtil.i("open app $appName")
            val isOpen:Boolean=AppHelper.launcherApp(appName)
            if(isOpen){
                addAiText("正在为您打开$appName")
//                VoiceManager.ttsStart("正在为您打开$appName")
            }else{
                addAiText("很抱歉,无法为您打开$appName")
//                VoiceManager.ttsStart("很抱歉,无法为您打开$appName")
            }
        }

        hideWindow()
    }

    //卸载App
    override fun unInstanllApp(appName: String) {
        if(!TextUtils.isEmpty(appName)){
            LogUtil.i("unInstall App $appName")
            val isUnInstallApp:Boolean = AppHelper.unInstallApp(appName)
            if(isUnInstallApp){
                addAiText("正在为您卸载$appName")
//                VoiceManager.ttsStart("正在为您卸载$appName")
            }else{
                addAiText("很抱歉,无法为您卸载$appName")
//                VoiceManager.ttsStart("很抱歉,无法为您卸载$appName")
            }
        }
        hideWindow()
    }

    //其它App操作
    override fun otherApp(appName: String) {
        if(!TextUtils.isEmpty(appName)){
            LogUtil.i("other app $appName")
            val isIntent:Boolean=AppHelper.launcherAppStore(appName)
            if(isIntent){
                addAiText("正在操作$appName")
//                VoiceManager.ttsStart("正在操作$appName")
            }else{
                addAiText(WordsTools.noAnswerWords())
//                VoiceManager.ttsStart(WordsTools.noAnswerWords())
            }
        }
        hideWindow()
    }

    //查询天气
    override fun queryWeather() {
    }

    //无法回答
    override fun nluError() {
        addAiText(WordsTools.noAnswerWords())
//        VoiceManager.ttsStart(WordsTools.noAnswerWords())
    }

    /**
     * 添加我的文本
     */
    private fun addMineText(text: String) {
        val bean = ChatListData(AppConstants.TYPE_MINE_TEXT)
        bean.text = text
        baseAddItem(bean)

    }

    /**
     * 添加AI的文本
     */
    private fun addAiText(text: String) {
        val bean = ChatListData(AppConstants.TYPE_AI_TEXT)
        bean.text = text
        baseAddItem(bean)
        VoiceManager.ttsStart(text)
    }

    /**
     * 添加AI的文本
     */
    private fun addAiText(text: String,mOnTTSResultListner:VoiceTTS.OnTTSResultListener) {
        val bean = ChatListData(AppConstants.TYPE_AI_TEXT)
        bean.text = text
        baseAddItem(bean)
        VoiceManager.ttsStart(text,mOnTTSResultListner)
    }

    /**
     * 添加 基类
     */
    private fun baseAddItem(bean: ChatListData) {
        mList.add(bean)
        //局部刷新 刷新最后一行
        mChatAdapter.notifyItemInserted(mList.size - 1)
    }

    /**
     * 更新提示语
     */
    private fun updateTips(text:String){
        tvVoiceTips.text=text
    }
}